package com.ruoyi.web.controller.datastatistics;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.datastatistics.domain.CopyRate;
import com.ruoyi.datastatistics.service.ICopyRateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 抄表率Controller
 *
 * @author TsingYu
 * @date 2024-08-02
 */
@RestController
@RequestMapping("/datastatistics/copyRate")
public class CopyRateController extends BaseController {
    private final ICopyRateService copyRateService;

    public CopyRateController(ICopyRateService copyRateService) {
        this.copyRateService = copyRateService;
    }

    /**
     * 查询抄表率列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:copyRate:list')")
    @GetMapping("/list")
    public TableDataInfo list(CopyRate copyRate) {
        LambdaQueryWrapper<CopyRate> wrapper = getWrapper(copyRate);
        startPage();
        List<CopyRate> list = copyRateService.list(wrapper);
        // 不分页的符合条件的list，算总的抄表率
        List<CopyRate> sumGroupBySheetsList = getTotalCopyRateBySheets(copyRate);
        setTotalCopyRate(list, sumGroupBySheetsList);
        return getDataTable(list);
    }

    /**
     * 查询抄表率区域总和列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:copyRate:list')")
    @GetMapping("/listGroupBySheetsId")
    public TableDataInfo listGroupBySheetsId(CopyRate copyRate) {
        startPage();
        List<CopyRate> list = getTotalCopyRateBySheets(copyRate);
        return getDataTable(list);
    }

    /**
     * 导出抄表率列表
     */
    @PreAuthorize("@ss.hasPermi('datastatistics:copyRate:export')")
    @Log(title = "抄表率", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CopyRate copyRate) {
        LambdaQueryWrapper<CopyRate> wrapper = getWrapper(copyRate);
        List<CopyRate> list = copyRateService.list(wrapper);
        setTotalCopyRate(list, getTotalCopyRateBySheets(copyRate));
        ExcelUtil<CopyRate> util = new ExcelUtil<>(CopyRate.class);
        util.exportExcel(response, list, "区域抄表率数据");
    }

    /**
     * 获取查询条件Wrapper
     *
     * @param copyRate 查询条件
     * @return Wrapper
     */
    private LambdaQueryWrapper<CopyRate> getWrapper(CopyRate copyRate) {
        SysUser user = getLoginUser().getUser();
        LambdaQueryWrapper<CopyRate> wrapper = Wrappers.lambdaQuery();
        wrapper.select(CopyRate::getSheetsId, CopyRate::getSheetsCode, CopyRate::getSheetsName, CopyRate::getCopyRate, CopyRate::getTerminalType, CopyRate::getDate, CopyRate::getCopyCount, CopyRate::getTotalCount, CopyRate::getCreateTime, CopyRate::getUpdateTime);
        wrapper.eq(copyRate.getTerminalType() != null, CopyRate::getTerminalType, copyRate.getTerminalType());
        wrapper.in(CollectionUtils.isNotEmpty(copyRate.getSheetsIds()), CopyRate::getSheetsId, copyRate.getSheetsIds());
        if (Constants.SYS_FLAG_ADMIN != user.getSystemFlag()) {
            if (CopyRate.TERMINAL_TYPE_DB == copyRate.getTerminalType()) {
                wrapper.inSql(CopyRate::getSheetsId, String.format("select tsu.sheetid from t_sheets_users tsu where tsu.sys_userid = %d and exists(select ts.id from t_sheets ts where ts.id = tsu.sheetid and ts.del_flag = 0)", user.getUserId()));
            } else {
                wrapper.inSql(CopyRate::getSheetsId, String.format("select s.id from t_sheets s inner join t_sheets_users tsu on s.parent_id = tsu.sheetid where tsu.sys_userid = %d", user.getUserId()));
            }

        }
        if (Constants.SYS_FLAG_NORMAL_USER == user.getSystemFlag()) {
            wrapper.inSql(CopyRate::getSheetsId, String.format("select id from t_sheets where tenant_id = '%s'", user.getTenantId()));
        }
        wrapper.ne(CopyRate::getSheetsId, -1L);
        wrapper.ge(StringUtils.isNotBlank(copyRate.getBeginDate()), CopyRate::getDate, copyRate.getBeginDate());
        wrapper.le(StringUtils.isNotBlank(copyRate.getEndDate()), CopyRate::getDate, copyRate.getEndDate());
        wrapper.likeRight(StringUtils.isNotBlank(copyRate.getSheetsCode()), CopyRate::getSheetsCode, copyRate.getSheetsCode());
        wrapper.like(StringUtils.isNotBlank(copyRate.getSheetsName()), CopyRate::getSheetsName, copyRate.getSheetsName());
        wrapper.ge(copyRate.getCopyRateMin() != null, CopyRate::getCopyRate, copyRate.getCopyRateMin());
        wrapper.le(copyRate.getCopyRateMax() != null, CopyRate::getCopyRate, copyRate.getCopyRateMax());
        wrapper.isNotNull(CopyRate::getCopyCount);
        return wrapper;
    }


    @PostMapping("/addCopyRate")
    public AjaxResult addCopyRate(String date, Integer terminalType) {
        return toAjax(copyRateService.addCopyDataByDate(date, terminalType));
    }


    private List<CopyRate> getTotalCopyRateBySheets(CopyRate copyRate) {
        LambdaQueryWrapper<CopyRate> wrapper = getWrapper(copyRate);
        wrapper.select(CopyRate::getSheetsId, CopyRate::getSheetsName, CopyRate::getSheetsCode, CopyRate::getCopyCountSum, CopyRate::getTotalCountSum)
                .groupBy(Arrays.asList(CopyRate::getSheetsId, CopyRate::getSheetsName, CopyRate::getSheetsCode));
        List<CopyRate> list = copyRateService.list(wrapper);
        list.forEach(e -> {
            if (e.getTotalCountSum() == 0) {
                e.setTotalCopyRate(null);
            } else {
                BigDecimal copyCountSum = new BigDecimal(e.getCopyCountSum());
                BigDecimal totalCountSum = new BigDecimal(e.getTotalCountSum());
                e.setTotalCopyRate(copyCountSum.divide(totalCountSum, 4, RoundingMode.HALF_UP));
            }
        });
        return list;
    }

    /**
     * 计算每个地区总的抄表率
     *
     * @param list                 需要设置总抄表率值的list
     * @param sumGroupBySheetsList 分区域计算总和的list
     */
    private void setTotalCopyRate(List<CopyRate> list, List<CopyRate> sumGroupBySheetsList) {
        if (CollectionUtils.isEmpty(list) || CollectionUtils.isEmpty(sumGroupBySheetsList)) {
            return;
        }
        for (CopyRate sum : sumGroupBySheetsList) {
            for (CopyRate rate : list) {
                if (Objects.equals(sum.getSheetsId(), rate.getSheetsId())) {
                    rate.setTotalCopyRate(sum.getTotalCopyRate());
                }
            }
        }
    }
}
